package com.example.xxcjgl.data.repository

import com.example.xxcjgl.data.api.RetrofitClient
import com.example.xxcjgl.data.models.Score
import com.example.xxcjgl.data.models.Student
import java.text.SimpleDateFormat
import java.util.Date
import javax.inject.Inject

class StudentRepositoryImpl @Inject constructor() : StudentRepository {

    override suspend fun getAllStudents(): List<Student> {
        try {
            val response = RetrofitClient.apiService.getStudents("")
            return if (response.success) {
                response.data ?: emptyList()
            } else {
                emptyList()
            }
        } catch (e: Exception) {
            throw Exception("获取学生列表失败: ${e.message}")
        }
    }

    override suspend fun addStudent(student: Student) {
        try {
            // 这里需要根据您的实际API来调整
            // 假设有一个添加学生的API
            val response = RetrofitClient.apiService.addStudent(student)
            if (!response.success) {
                throw Exception(response.message ?: "添加学生失败")
            }
        } catch (e: Exception) {
            throw Exception("添加学生失败: ${e.message}")
        }
    }

    override suspend fun addScore(
        studentId: String,
        mathScore: Float,
        chineseScore: Float,
        useEncryption: Boolean,
        encryptionKey: String?
    ) {
        try {
            // 获取当前日期作为考试日期
            val currentDate = SimpleDateFormat("yyyy-MM-dd").format(Date())

            // 创建 Score 对象
            val scoreData = Score(
                studentId = studentId,
                mathScore = mathScore,
                chineseScore = chineseScore,
                examDate = currentDate,
                useEncryption = if (useEncryption) 1 else 0,
                encryptionKey = encryptionKey
            )

            val response = RetrofitClient.apiService.addScore(scoreData)

            if (!response.success) {
                throw Exception(response.message ?: "添加成绩失败")
            }
        } catch (e: Exception) {
            throw Exception("添加成绩失败: ${e.message}")
        }
    }
}